package com.xc.quickstart.job.controller;

import com.xc.quickstart.common.context.JobContext;
import com.xc.quickstart.common.model.ApiResponse;
import com.xc.quickstart.common.model.JobContextModel;
import com.xc.quickstart.job.BaseJobHandler;
import com.xc.quickstart.job.FileJobProcessor;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

@RequestMapping(value = "/job/any/file/{jobName}")
@Slf4j
@RestController
@Api(description = "任意任务", tags = "job")
public class AnyFileJobController {

    @Autowired
    private DefaultListableBeanFactory beanFactory;

    @ApiOperation(value = "执行", notes = "执行简单示例任务")
    @RequestMapping(value = "/execute", method = {RequestMethod.POST, RequestMethod.GET})
    public ApiResponse execute(
            @ApiParam("任务名称") @PathVariable("jobName") String jobName,
            @ApiParam("参数") @RequestParam Map<String, String> args,
            @ApiParam("文件") @RequestParam("file") MultipartFile file) {

        String realJobName = jobName.concat("JobHandler");
        if (!beanFactory.containsBean(realJobName)) {
            return ApiResponse.fail(String.format("没有找到实现,%s", realJobName));
        }

        JobContextModel jobContextModel = JobContextModel.builder().file(file).build();
        JobContext.setJobContextModel(jobContextModel);

        BaseJobHandler jobHandler = (BaseJobHandler) beanFactory.getBean(realJobName);

        if (!(jobHandler instanceof FileJobProcessor)) {
            return ApiResponse.fail(String.format("没有找到FileJobProcessor的接口实现,%s", realJobName));
        }

        jobHandler.asyncExecute(args);
        return ApiResponse.ok();
    }
}
